#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI童话书Web界面
基于Flask的交互式Web应用
"""

from flask import Flask, render_template, request, jsonify, session
import asyncio
import json
from ai_fairy_tale_book import FairyTaleBookApp, UserProfile
import uuid
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'fairy_tale_secret_key_2024'

# 全局应用实例
fairy_tale_app = None

@app.before_first_request
async def initialize_app():
    """初始化应用"""
    global fairy_tale_app
    fairy_tale_app = FairyTaleBookApp()
    await fairy_tale_app.initialize()

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/create_profile', methods=['POST'])
def create_profile():
    """创建用户画像"""
    try:
        data = request.json
        name = data.get('name')
        age = int(data.get('age'))
        interests = data.get('interests', [])
        learning_goals = data.get('learning_goals', [])
        
        # 创建用户画像
        user_profile = fairy_tale_app.create_user_profile(name, age, interests, learning_goals)
        
        # 保存到session
        session['user_id'] = str(uuid.uuid4())
        session['user_profile'] = {
            'name': user_profile.name,
            'age': user_profile.age,
            'interests': user_profile.interests,
            'learning_goals': user_profile.learning_goals
        }
        
        return jsonify({
            'success': True,
            'message': f'欢迎 {name}！你的专属童话世界已经准备好了！',
            'user_profile': session['user_profile']
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/start_story', methods=['POST'])
async def start_story():
    """开始新故事"""
    try:
        if 'user_profile' not in session:
            return jsonify({'success': False, 'error': '请先创建用户画像'})
        
        data = request.json
        story_type = data.get('story_type', 'adventure')
        
        # 开始新故事
        current_node = await fairy_tale_app.start_new_story(story_type)
        
        # 保存当前状态到session
        session['current_story_state'] = {
            'current_node_id': current_node.id,
            'story_type': story_type,
            'start_time': datetime.now().isoformat()
        }
        
        return jsonify({
            'success': True,
            'story_node': {
                'id': current_node.id,
                'title': current_node.title,
                'content': current_node.content,
                'choices': current_node.choices,
                'knowledge_points': current_node.knowledge_points,
                'educational_value': current_node.educational_value,
                'difficulty_level': current_node.difficulty_level
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/make_choice', methods=['POST'])
async def make_choice():
    """做出选择"""
    try:
        if 'user_profile' not in session:
            return jsonify({'success': False, 'error': '请先创建用户画像'})
        
        data = request.json
        choice_index = int(data.get('choice_index'))
        
        # 做出选择
        next_node, analysis = await fairy_tale_app.make_choice(choice_index)
        
        # 更新session状态
        session['current_story_state']['current_node_id'] = next_node.id
        
        return jsonify({
            'success': True,
            'next_node': {
                'id': next_node.id,
                'title': next_node.title,
                'content': next_node.content,
                'choices': next_node.choices,
                'knowledge_points': next_node.knowledge_points,
                'educational_value': next_node.educational_value,
                'difficulty_level': next_node.difficulty_level
            },
            'analysis': analysis
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/get_learning_report')
def get_learning_report():
    """获取学习报告"""
    try:
        if 'user_profile' not in session:
            return jsonify({'success': False, 'error': '请先创建用户画像'})
        
        report = fairy_tale_app.get_learning_report()
        return jsonify({'success': True, 'report': report})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/get_story_types')
def get_story_types():
    """获取故事类型"""
    story_types = [
        {
            'id': 'adventure',
            'name': '冒险探索',
            'description': '勇敢的冒险之旅，培养勇气和探索精神',
            'suitable_age': '3-14岁',
            'icon': '🗺️'
        },
        {
            'id': 'learning',
            'name': '知识探索',
            'description': '有趣的学习之旅，在故事中掌握新知识',
            'suitable_age': '5-14岁',
            'icon': '📚'
        },
        {
            'id': 'friendship',
            'name': '友谊故事',
            'description': '温暖的友谊故事，学会分享与合作',
            'suitable_age': '3-12岁',
            'icon': '👫'
        },
        {
            'id': 'science',
            'name': '科学奇遇',
            'description': '神奇的科学世界，探索自然的奥秘',
            'suitable_age': '6-14岁',
            'icon': '🔬'
        },
        {
            'id': 'history',
            'name': '历史穿越',
            'description': '穿越时空的历史之旅，了解古今文明',
            'suitable_age': '8-14岁',
            'icon': '🏛️'
        }
    ]
    
    return jsonify({'success': True, 'story_types': story_types})

if __name__ == '__main__':
    # 创建异步事件循环
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    
    # 初始化应用
    loop.run_until_complete(initialize_app())
    
    # 启动Flask应用
    app.run(debug=True, host='0.0.0.0', port=5000)